<?php
namespace Game\Service;
use Think\Model;
/**
 * 自定义页面模型
 */
class GameMapConfigService extends Model{
    /**
     * 地图配置转成json
     * @param mixed $stage_id
     * @return $map_config_json
     */
    public function get_map_config_json($stage_id){
        if(!$stage_id){
            return false;
        }
        $res = D('GameMapConfig')->get_config_data($stage_id)['config_data'];
        $res = json_decode($res,true);
        // 地图配置最后写在这里
        $map_config = [];
        $global_config = [];
        $track_config = [];
        $items = [];
        foreach($res as $k => $v){
            foreach($v as $k2 => $v2){
                if(json_decode($v2) != null){
                    $v[$k2] = json_decode($v2,true);
                }
            }
            // 单独处理全局配置项
            if($v['type'] == 'config'){
                unset($v['type']);
                unset($v['component']);
                foreach($v as $k3 => $v3){
                    $global_config[$k3] = $v3;
                }
            }else if($v['type'] == 'trackConfig'){
                // 分段跑道配置
                $tmp = [
                    'pos' => $v['pos'],
                    'length' => $v['length'],
                    'col' => $v['col']
                ];
                $track_config[] = $tmp;
                unset($$v['type']);
            }else{
                // 其他是道具
                $items[] = $v;
            }
        }
        $map_items = [];
        // 根据全局配置和分段跑道配置完成道具配置
        foreach($items as $k => $v){
            $item = [];
            $item['pos'] = explode(',', $v['pos']);
            $item['pos'] = array_map('intval', $item['pos']);
            // 根据分段跑道配置设置分段的Col，如果没有就是baseCol
            $item['col'] = $global_config['baseCol'];
            if($track_config){
                if(($item['pos'][0] >= $v2['pos']) && ($item['pos'][0] <= ($v2['pos'] + $v2['length']))){
                    $item['col'] = $v2['col'];
                    break;
                }
            }
            unset($v['pos']);
            // X转成数组
            if($v['x']){
                $item['x'] = explode(',', $v['x']);
                $item['x'] = array_map('intval', $item['x']);
            }else{
                $item['x'] = range(1, $item['col']);
            }
            unset($v['x']);
            $item['type'] = $v['component'];
            unset($v['component']);
            $item['params'] = $v;
            $map_items[] = $item;
        }
        $map_config['config'] = $global_config;
        $map_config['items'] = $map_items;
        return $map_config;
    }
}